﻿using DataAccessObjectLayer.Properties;
using System;
using System.Configuration;
using System.Data.Common;

namespace DataAccessObjectLayer
{
    public class DBCon
    {
        /// <summary>
        /// Constructor for DBCon Sets the connectionstring regarding to the chosen .config.
        ///
        /// The DBProviderfactory is used for generic implementation of the DBConnection, making it
        /// easier to change the type of DBConnection later
        /// </summary>
        public DbConnection GetConnection()
        {
            //Use this for local database

            var connectionString = Settings.Default.conStringLocalDB;
            var providerName = Settings.Default.providerLocalDB;

            //Use this for connection to balder
            /*
            var connectionString = Settings.Default.conStringBalder;
            var providerName = Settings.Default.providerBalder;
            */
            // Assume failure.
            DbConnection connection = null;

            // Create the DbProviderFactory and DbConnection.
            if (connectionString != null)
            {
                DbProviderFactory factory =
                    DbProviderFactories.GetFactory(providerName);

                connection = factory.CreateConnection();
                if (connection != null)
                {
                    connection.ConnectionString = connectionString;
                }
                else
                {
                    throw new Exception("connection could not be made with DBProviderFactory");
                }
            }
            // Return the connection.
            return connection;
        }

        /// <summary>
        /// Shows the connection status in TUI implementations.
        /// </summary>
        private static void ShowConnectionStatus(DbConnection cn)
        {
            try
            {
                // Show various stats about current connection object.
                Console.WriteLine("***** Info about your connection *****");
                Console.WriteLine("Database location: {0}", cn.DataSource);
                Console.WriteLine("Database name: {0}", cn.Database);
                Console.WriteLine("Timeout: {0}", cn.ConnectionTimeout);
                Console.WriteLine("Connection state: {0}\n", cn.State);
            }
            catch (Exception e)
            {
                Console.WriteLine(e.ToString());
            }
        }
    }
}